<template>
	<picker :value="value" mode="selector" :range="range" range-key="name" @change="change">
		<fui-form-item label="支付途径" asterisk arrow highlight>
			<view v-if="value===undefined" class="fs-color__label">请选择支付途径</view>
			<view v-else>{{label}}</view>
		</fui-form-item>
	</picker>
</template>

<script setup>
	import { onMounted, ref, watch } from 'vue';
	import { fetchPayMethodList } from '@/common/api/index.js';

	const payment_way = defineModel('payment_way')

	const range = ref([])
	const value = ref()


	async function getPayMethodList() {
		const { success, data } = await fetchPayMethodList();
		if (success) {
			range.value = data;
		}
	}


	const change = (e) => {
		value.value = e.detail.value
	}

	const label = ref('')
	watch(value, (val) => {
		if (val !== undefined) {
			label.value = range.value[val].name
			payment_way.value = range.value[val].id
		}
	}, { immediate: true })

	onMounted(async () => {
		await getPayMethodList();
		if (payment_way.value) {
			if (range.value.length > 0) {
				const index = range.value.findIndex(em => String(em.id) === String(payment_way.value))
				if (index !== -1) {
					value.value = index
				} else {
					payment_way.value = ''
				}
			}

		}
	})
</script>

<style>
</style>